import Vue from 'vue'
import VueRouter from 'vue-router'

// // 一级
// import Login from '@/views/Login.vue'
// import Register from '@/views/Register.vue'
// import Layout from '@/views/Layout.vue'
// import Detail from '@/views/Detail.vue'

// // 二级
// import Like from '@/views/Like'
// import Article from '@/views/Article'
// import Collect from '@/views/Collect'
// import User from '@/views/User'
// import { getToken } from '@/utils/storage'

import { getToken } from '@/utils/storage'

import Layout from '@/views/Layout.vue'
const Detail = () => import('@/views/Detail.vue')
const Register = () => import('@/views/Register.vue')
const Login = () => import('@/views/Login.vue')
const Article = () => import('@/views/Article.vue')
const Collect = () => import('@/views/Collect.vue')
const Like = () => import('@/views/Like.vue')
const User = () => import('@/views/User.vue')
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    { path: '/article/:id', component: Detail },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '/', redirect: '/article' },
        { path: 'article', component: Article },
        { path: 'collect', component: Collect },
        { path: 'like', component: Like },
        { path: 'user', component: User }
      ]
    }
  ]
})

// 白名单
const whiteList = ['/login', '/register']

/**
 * 配置路由的全局前置守卫
 * to   往哪里去， 到哪去的路由信息对象
 * from 从哪里来， 从哪来的路由信息对象
 * next() 是否放行   如果next()调用，就是放行 / next(路径) 拦截到某个路径页面
 */
router.beforeEach((to, from, next) => {
  // 1. 获取token
  const token = getToken()
  // 2. 判断是否有token
  if (token) {
    // 2.2 判断是否去登录页
    if (to.path === '/login' || to.path === '/register') {
      next('/')
    } else {
      // 2.1 直接放行
      next()
    }
  } else {
    // 2.2 判断要去的页面路径是否在白名单中
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
